/*******************************************************************************
 * Copyright 2011, 2012 Chris Banes.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.chrisbanes.photoview;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Matrix.ScaleToFit;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;

import androidx.core.view.MotionEventCompat;

import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewParent;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.OverScroller;

import static android.view.View.OnClickListener;

import com.lib.utils.XLog;

/**
 * The component of {@link PhotoView} which does the work allowing for zooming, scaling, panning, etc.
 * It is made public in case you need to subclass something other than {@link ImageView} and still
 * gain the functionality that {@link PhotoView} offers
 */
public class PhotoViewEventHandler implements View.OnTouchListener, View.OnLayoutChangeListener, PhotoGestureDetector.OnGestureListener {

    private static int DEFAULT_ZOOM_DURATION = 200;

    private static final int EDGE_NONE = -1;

    private static final int EDGE_LEFT = 0;

    private static final int EDGE_RIGHT = 1;

    private static final int EDGE_BOTH = 2;

    private static float DEFAULT_MAX_SCALE = 7f;
    private static float DEFAULT_MID_SCALE = 3f;
    private static float DEFAULT_MIN_SCALE = 0.2f;
    private static float DEFAULT_NO_SCALE = 1f;

    private static final float OVER_MAX_SCALE = DEFAULT_MAX_SCALE * 3;

    private int mZoomDuration = DEFAULT_ZOOM_DURATION;

    private float mMaxScale = DEFAULT_MAX_SCALE;
    private float mMidScale = DEFAULT_MID_SCALE;
    private float mMinScale = DEFAULT_MIN_SCALE;

    private PhotoView mImageView;

    private float mBaseRotation;

    private int mScrollEdge = EDGE_BOTH;

    private boolean mZoomEnabled = true;

    private FlingRunnable mFlingRunnable;

    private ScaleType mScaleType = ScaleType.FIT_CENTER;

    // Gesture Detectors
    private GestureDetector mGestureDetector;

    private PhotoGestureDetector mScaleDragDetector;

    // These are set so we don't keep allocating them on the heap
    private final Matrix mBaseMatrix = new Matrix();

    private final Matrix mDrawMatrix = new Matrix();

    private final Matrix mSuppMatrix = new Matrix();

    private final RectF mDisplayRect = new RectF();

    private final float[] mMatrixValues = new float[9];

    // Listeners

    private OnClickListener mOnClickListener;

    private OnLongClickListener mOnLongClickListener;

    private OnScalingListener mOnScalingListener;

    private OnPhotoTapListener mOnPhotoTapListener;

    private OnSingleFlingListener mOnSingleFlingListener;

    private OnMatrixChangedListener mOnMatrixChangedListener;

    private OnOutsidePhotoTapListener mOnOutsidePhotoTapListener;

    // Interpolator
    private Interpolator mInterpolator = new AccelerateDecelerateInterpolator();

    private boolean mCmdMode;

    public void setCmdMode(boolean cmdMode) {
        mCmdMode = cmdMode;
    }

    /**
     * SetCallback when the user tapped outside of the photo
     */
    public interface OnOutsidePhotoTapListener {

        /**
         * The outside of the photo has been tapped
         */
        void onOutsidePhotoTap();
    }

    /**
     * Interface definition for a callback to be invoked when the internal Matrix has changed for
     * this View.
     *
     * @author Chris Banes
     */
    public interface OnMatrixChangedListener {

        /**
         * SetCallback for when the Matrix displaying the Drawable has changed. This could be because
         * the View's bounds have changed, or the user has zoomed.
         *
         * @param rect - Rectangle displaying the Drawable's new bounds.
         */
        void onChanged(RectF rect);
    }

    /**
     * Interface definition for callback to be invoked when attached ImageView scale changes
     *
     * @author Marek Sebera
     */
    public interface OnScalingListener {

        /**
         * SetCallback for when the scale changes
         *
         * @param scaleFactor the scale factor (less than 1 for zoom out, greater than 1 for zoom in)
         * @param focusX      focal point X position
         * @param focusY      focal point Y position
         */
        void onScaling(float scaleFactor, float focusX, float focusY);
    }

    /**
     * A callback to be invoked when the ImageView is flung with a single
     * touch
     */
    public interface OnSingleFlingListener {

        /**
         * A callback to receive where the user flings on a ImageView. You will receive a callback if
         * the user flings anywhere on the view.
         *
         * @param e1        - MotionEvent the user first touch.
         * @param e2        - MotionEvent the user last touch.
         * @param velocityX - distance of user's horizontal fling.
         * @param velocityY - distance of user's vertical fling.
         */
        boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
    }

    /**
     * A callback to be invoked when the Photo is tapped with a single
     * tap.
     */
    public interface OnPhotoTapListener {

        /**
         * A callback to receive where the user taps on a photo. You will only receive a callback if
         * the user taps on the actual photo, tapping on 'whitespace' will be ignored.
         *
         * @param view - ImageView the user tapped.
         * @param x    - where the user tapped from the of the Drawable, as percentage of the
         *             Drawable width.
         * @param y    - where the user tapped from the top of the Drawable, as percentage of the
         *             Drawable height.
         */
        void onPhotoTap(PhotoView view, float x, float y);
    }

    public void setOnLongClickListener(OnLongClickListener listener) {

        mOnLongClickListener = listener;
    }

    public void setOnClickListener(OnClickListener listener) {

        mOnClickListener = listener;
    }

    public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {

        mOnMatrixChangedListener = listener;
    }

    public void setOnPhotoTapListener(OnPhotoTapListener listener) {
        mOnPhotoTapListener = listener;
    }

    public void setOnOutsidePhotoTapListener(OnOutsidePhotoTapListener mOutsidePhotoTapListener) {

        this.mOnOutsidePhotoTapListener = mOutsidePhotoTapListener;
    }

    public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) {

        this.mGestureDetector.setOnDoubleTapListener(newOnDoubleTapListener);
    }

    public void setOnScaleChangeListener(OnScalingListener onScaleChangeListener) {

        this.mOnScalingListener = onScaleChangeListener;
    }

    public void setOnSingleFlingListener(OnSingleFlingListener onSingleFlingListener) {

        this.mOnSingleFlingListener = onSingleFlingListener;
    }

    public PhotoViewEventHandler(PhotoView imageView) {

        mImageView = imageView;
        imageView.setOnTouchListener(this);
        imageView.addOnLayoutChangeListener(this);

        if (imageView.isInEditMode()) {
            return;
        }

        // Create Gesture Detectors...
        Context context = imageView.getContext();
        mScaleDragDetector = new PhotoGestureDetector(context, this);

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {

            // forward long click listener
            @Override
            public void onLongPress(MotionEvent e) {

                if (null != mOnLongClickListener) {
                    mOnLongClickListener.onLongClick(mImageView);
                }
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

                if (mOnSingleFlingListener != null) {
                    if (getScale() > DEFAULT_NO_SCALE) {
                        return false;
                    }

                    if (MotionEventCompat.getPointerCount(e1) > 1 ||
                            MotionEventCompat.getPointerCount(e2) > 1) {
                        return false;
                    }

                    return mOnSingleFlingListener.onFling(e1, e2, velocityX, velocityY);
                }
                return false;
            }
        });

        mGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() {

            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if (mOnClickListener != null) {
                    mOnClickListener.onClick(mImageView);
                }
                if (mOnPhotoTapListener != null) {
                    final RectF displayRect = getDisplayRect();

                    if (null != displayRect) {
                        final float x = e.getX(), y = e.getY();
                        // Check to see if the user tapped on the photo
                        if (displayRect.contains(x, y)) {
                            float xResult = (x - displayRect.left) / displayRect.width();
                            float yResult = (y - displayRect.top) / displayRect.height();
                            mOnPhotoTapListener.onPhotoTap(mImageView, xResult, yResult);
                            return true;
                        } else {
                            if (mOnOutsidePhotoTapListener != null) {
                                mOnOutsidePhotoTapListener.onOutsidePhotoTap();
                            }
                        }
                    }
                }
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent event) {
                float scale = getScale();
                float x = event.getX();
                float y = event.getY();

                if (scale < mMidScale) {
                    setScale(mMidScale, x, y, true);
                } else if (scale >= mMidScale && scale < mMaxScale) {
                    setScale(mMaxScale, x, y, true);
                } else {
                    setScale(DEFAULT_NO_SCALE, x, y, true);
                }
                return true;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                // Wait for the confirmed onDoubleTap() instead
                return false;
            }
        });
    }

    public boolean isZoomEnabled() {

        return mZoomEnabled;
    }

    public RectF getDisplayRect() {

        checkMatrixBounds();
        return getDisplayRect(getDrawMatrix());
    }

    public boolean setDisplayMatrix(Matrix finalMatrix) {

        if (finalMatrix == null) {
            throw new IllegalArgumentException("Matrix cannot be null");
        }

        if (mImageView.getDrawable() == null) {
            return false;
        }

        mSuppMatrix.set(finalMatrix);
        setImageViewMatrix(getDrawMatrix());
        checkMatrixBounds();

        return true;
    }

    public void setBaseRotation(final float degrees) {

        mBaseRotation = degrees % 360;
        update();
        setRotationBy(mBaseRotation);
        checkAndDisplayMatrix();
    }

    public void setRotationTo(float degrees) {

        mSuppMatrix.setRotate(degrees % 360);
        checkAndDisplayMatrix();
    }

    public void setRotationBy(float degrees) {

        mSuppMatrix.postRotate(degrees % 360);
        checkAndDisplayMatrix();
    }

    public float getScale() {

        return (float) Math.sqrt((float) Math.pow(getValue(mSuppMatrix, Matrix.MSCALE_X), 2) + (float) Math
                .pow(getValue(mSuppMatrix, Matrix.MSKEW_Y), 2));
    }

    public ScaleType getScaleType() {

        return mScaleType;
    }

    @Override
    public void onDrag(float dx, float dy) {
        if (mScaleDragDetector.isScaling()) {
            return; // Do not drag if we are already scaling
        }
        mSuppMatrix.postTranslate(dx, dy);
        checkAndDisplayMatrix();

        ViewParent parent = mImageView.getParent();
        /*只有两边显示才可让父类拦截事件 */
//        XLog.i(mScrollEdge + ", dx=" + dx + ", dy=" + dy);
        if (mScrollEdge == EDGE_BOTH
                /*|| (mScrollEdge == EDGE_LEFT && dx >= 1f)
                || (mScrollEdge == EDGE_RIGHT && dx <= -1f)*/) {

            if (null != parent) {
                parent.requestDisallowInterceptTouchEvent(false);
            }
        } else {
            if (null != parent) {
                parent.requestDisallowInterceptTouchEvent(true);
            }
        }
    }

    @Override
    public void onFling(float startX, float startY, float velocityX, float velocityY) {

        mFlingRunnable = new FlingRunnable(mImageView.getContext());
        mFlingRunnable.fling(getImageViewWidth(mImageView),
                getImageViewHeight(mImageView), (int) velocityX, (int) velocityY);
        mImageView.post(mFlingRunnable);
    }

    public void onScaling(float scaleFactor, float focusX, float focusY) {
        if (null != mOnScalingListener) {
            mOnScalingListener.onScaling(scaleFactor, focusX, focusY);
        }
        mSuppMatrix.postScale(scaleFactor, scaleFactor, focusX, focusY);
        checkAndDisplayMatrix();
    }

    @Override
    public void onScaleEnd(float focusX, float focusY) {
        float scale = getScale();
        if (scale < mMinScale) {
            setScale(mMinScale, focusX, focusY, true);
        } else if (scale >= OVER_MAX_SCALE) {
            setScale(OVER_MAX_SCALE, focusX, focusY, true);
        }
    }

    @Override
    public void onLayoutChange(View v, int l, int t, int r, int b, int ol, int ot, int or, int ob) {
        // Update our base matrix, as the bounds have changed
        updateBaseMatrix(mImageView.getDrawable());
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        boolean handled = false;
        if (mZoomEnabled && ((ImageView) view).getDrawable() != null) {
            ViewParent parent = view.getParent();
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:

                    // First, disable the Parent from intercepting the touch event
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(true);
                    }

                    // If we're flinging, and the user presses down, cancel fling
                    cancelFling();
                    break;

                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    // If the user has zoomed less than min scale, zoom back
                    // to min scale
                    if (getScale() < DEFAULT_NO_SCALE) {
                        RectF rect = getDisplayRect();
                        if (null != rect) {
                            view.post(new AnimatedZoomRunnable(getScale(), DEFAULT_NO_SCALE, rect.centerX(), rect.centerY()));
                            handled = true;
                        }
                    }
                    break;
            }

            // Try the Scale/Drag detector
            if (null != mScaleDragDetector) {
                handled = mScaleDragDetector.onTouchEvent(event);
            }
            // Check to see if the user double tapped
            if (null != mGestureDetector && mGestureDetector.onTouchEvent(event)) {
                handled = true;
            }
        }
        return handled;
    }

    /**
     * 缩放等级，请按从小到大的顺序，否则无效
     *
     * @param minimumScale 最小缩放值
     * @param mediumScale  中间缩放值
     * @param maximumScale 最大缩放值
     */
    public void setScaleLevels(float minimumScale, float mediumScale, float maximumScale) {
        if (minimumScale < mediumScale && mediumScale < maximumScale) {
            mMinScale = minimumScale;
            mMidScale = mediumScale;
            mMaxScale = maximumScale;
        }
    }

    public void setScale(float scale) {
        setScale(scale, false);
    }

    public void setScale(float scale, boolean animate) {
        setScale(scale, (mImageView.getRight()) / 2, (mImageView.getBottom()) / 2, animate);
    }

    public void setScale(float scale, float focalX, float focalY, boolean animate) {
        // Check to see if the scale is within bounds
        if (scale < mMinScale) {
            scale = mMinScale;
        } else if (scale > OVER_MAX_SCALE) {
            scale = OVER_MAX_SCALE;
        }
        if (animate) {
            mImageView.post(new AnimatedZoomRunnable(getScale(), scale, focalX, focalY));
        } else {
            mSuppMatrix.setScale(scale, scale, focalX, focalY);
            checkAndDisplayMatrix();
        }
    }

    /**
     * Set the zoom interpolator
     *
     * @param interpolator the zoom interpolator
     */
    public void setZoomInterpolator(Interpolator interpolator) {
        mInterpolator = interpolator;
    }

    public void setScaleType(ScaleType scaleType) {
        if (scaleType == null) {
            return;
        }
        if (scaleType == ScaleType.MATRIX) {
            throw new IllegalArgumentException("Matrix scale type is not supported");
        }

        if (scaleType != mScaleType) {
            mScaleType = scaleType;
            update();
        }
    }

    public void setZoomable(boolean zoomable) {

        mZoomEnabled = zoomable;
        update();
    }

    public void update() {

        if (mZoomEnabled) {
            // Update the base matrix using the current drawable
            updateBaseMatrix(mImageView.getDrawable());
        } else {
            // Reset the Matrix...
            resetMatrix();
        }
    }

    /**
     * Get the display matrix
     *
     * @param matrix target matrix to copy to
     */
    public void getDisplayMatrix(Matrix matrix) {

        matrix.set(getDrawMatrix());
    }

    /**
     * Get the current support matrix
     */
    public void getSuppMatrix(Matrix matrix) {

        matrix.set(mSuppMatrix);
    }

    private Matrix getDrawMatrix() {

        mDrawMatrix.set(mBaseMatrix);
        mDrawMatrix.postConcat(mSuppMatrix);
        return mDrawMatrix;
    }

    private void cancelFling() {

        if (null != mFlingRunnable) {
            mFlingRunnable.cancelFling();
            mFlingRunnable = null;
        }
    }

    public Matrix getImageMatrix() {

        return mDrawMatrix;
    }

    /**
     * Helper method that simply checks the Matrix, and then displays the result
     */
    private void checkAndDisplayMatrix() {
        if (checkMatrixBounds()) {
            setImageViewMatrix(getDrawMatrix());
        }
    }

    private boolean checkMatrixBounds() {
        final RectF rect = getDisplayRect(getDrawMatrix());
        if (rect == null) {
            return false;
        }

        final float height = rect.height(), width = rect.width();
        float deltaX = 0, deltaY = 0;

        final int viewHeight = getImageViewHeight(mImageView);
        if (height <= viewHeight) {
            switch (mScaleType) {
                case FIT_START:
                    deltaY = -rect.top;
                    break;
                case FIT_END:
                    deltaY = viewHeight - height - rect.top;
                    break;
                default:
                    deltaY = (viewHeight - height) / 2 - rect.top;
                    break;
            }
        } else if (rect.top > 0) {
            deltaY = -rect.top;
        } else if (rect.bottom < viewHeight) {
            deltaY = viewHeight - rect.bottom;
        }

        final int viewWidth = getImageViewWidth(mImageView);
        if (width <= viewWidth) {
            switch (mScaleType) {
                case FIT_START:
                    deltaX = -rect.left;
                    break;
                case FIT_END:
                    deltaX = viewWidth - width - rect.left;
                    break;
                default:
                    deltaX = (viewWidth - width) / 2 - rect.left;
                    break;
            }
            mScrollEdge = EDGE_BOTH;
        } else if (rect.left > 0) {
            mScrollEdge = EDGE_LEFT;
            deltaX = -rect.left;
        } else if (rect.right < viewWidth) {
            deltaX = viewWidth - rect.right;
            mScrollEdge = EDGE_RIGHT;
        } else {
            mScrollEdge = EDGE_NONE;
        }

        // Finally actually translate the matrix
        mSuppMatrix.postTranslate(deltaX, deltaY);
        return true;
    }

    /**
     * Helper method that maps the supplied Matrix to the current Drawable
     *
     * @param matrix - Matrix to map Drawable against
     * @return RectF - Displayed Rectangle
     */
    private RectF getDisplayRect(Matrix matrix) {

        Drawable d = mImageView.getDrawable();
        if (null != d) {
            mDisplayRect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            matrix.mapRect(mDisplayRect);
            return mDisplayRect;
        }
        return null;
    }

    public void setZoomTransitionDuration(int milliseconds) {

        mZoomDuration = milliseconds;
    }

    /**
     * Helper method that 'unpacks' a Matrix and returns the required value
     *
     * @param matrix     - Matrix to unpack
     * @param whichValue - Which value from Matrix.M* to return
     * @return float - returned value
     */
    private float getValue(Matrix matrix, int whichValue) {

        matrix.getValues(mMatrixValues);
        return mMatrixValues[whichValue];
    }

    /**
     * Resets the Matrix back to FIT_CENTER, and then displays it.s
     */
    private void resetMatrix() {

        mSuppMatrix.reset();
        setRotationBy(mBaseRotation);
        setImageViewMatrix(getDrawMatrix());
        checkMatrixBounds();
    }

    private void setImageViewMatrix(Matrix matrix) {

        mImageView.setImageMatrix(matrix);

        // Call MatrixChangedListener if needed
        if (mOnMatrixChangedListener != null) {
            RectF displayRect = getDisplayRect(matrix);
            if (null != displayRect) {
                mOnMatrixChangedListener.onChanged(displayRect);
            }
        }
    }

    /**
     * Calculate Matrix for FIT_CENTER
     *
     * @param drawable - Drawable being displayed
     */
    private void updateBaseMatrix(Drawable drawable) {

        if (drawable == null) {
            return;
        }

        final float viewWidth = getImageViewWidth(mImageView);
        final float viewHeight = getImageViewHeight(mImageView);
        final int drawableWidth = drawable.getIntrinsicWidth();
        final int drawableHeight = drawable.getIntrinsicHeight();

        mBaseMatrix.reset();

        final float widthScale = viewWidth / drawableWidth;
        final float heightScale = viewHeight / drawableHeight;

        if (mScaleType == ScaleType.CENTER) {
            mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2F,
                    (viewHeight - drawableHeight) / 2F);

        } else if (mScaleType == ScaleType.CENTER_CROP) {
            float scale = Math.max(widthScale, heightScale);
            mBaseMatrix.postScale(scale, scale);
            mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
                    (viewHeight - drawableHeight * scale) / 2F);

        } else if (mScaleType == ScaleType.CENTER_INSIDE) {
            float scale = Math.min(1.0f, Math.min(widthScale, heightScale));
            mBaseMatrix.postScale(scale, scale);
            mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F,
                    (viewHeight - drawableHeight * scale) / 2F);

        } else {
            RectF mTempSrc = new RectF(0, 0, drawableWidth, drawableHeight);
            RectF mTempDst = new RectF(0, 0, viewWidth, viewHeight);

            if ((int) mBaseRotation % 180 != 0) {
                mTempSrc = new RectF(0, 0, drawableHeight, drawableWidth);
            }

            switch (mScaleType) {
                case FIT_CENTER:
                    mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);
                    break;

                case FIT_START:
                    mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);
                    break;

                case FIT_END:
                    mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);
                    break;

                case FIT_XY:
                    mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL);
                    break;

                default:
                    break;
            }
        }

        resetMatrix();
    }

    private int getImageViewWidth(ImageView imageView) {

        return imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
    }

    private int getImageViewHeight(ImageView imageView) {

        return imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom();
    }

    private class AnimatedZoomRunnable implements Runnable {

        private final float mFocalX, mFocalY;

        private final long mStartTime;

        private final float mZoomStart, mZoomEnd;

        public AnimatedZoomRunnable(final float currentZoom, final float targetZoom,
                                    final float focalX, final float focalY) {

            mFocalX = focalX;
            mFocalY = focalY;
            mStartTime = System.currentTimeMillis();
            mZoomStart = currentZoom;
            mZoomEnd = targetZoom;
        }

        @Override
        public void run() {

            float t = interpolate();
            float scale = mZoomStart + t * (mZoomEnd - mZoomStart);
            float deltaScale = scale / getScale();

            onScaling(deltaScale, mFocalX, mFocalY);

            // We haven't hit our target scale yet, so post ourselves again
            if (t < 1f) {
                Compat.postOnAnimation(mImageView, this);
            }
        }

        private float interpolate() {

            float t = 1f * (System.currentTimeMillis() - mStartTime) / mZoomDuration;
            t = Math.min(1f, t);
            t = mInterpolator.getInterpolation(t);
            return t;
        }
    }

    private class FlingRunnable implements Runnable {

        private final OverScroller mScroller;

        private int mCurrentX, mCurrentY;

        public FlingRunnable(Context context) {

            mScroller = new OverScroller(context);
        }

        public void cancelFling() {

            mScroller.forceFinished(true);
        }

        public void fling(int viewWidth, int viewHeight, int velocityX,
                          int velocityY) {

            final RectF rect = getDisplayRect();
            if (null == rect) {
                return;
            }

            final int startX = Math.round(-rect.left);
            final int minX, maxX, minY, maxY;

            if (viewWidth < rect.width()) {
                minX = 0;
                maxX = Math.round(rect.width() - viewWidth);
            } else {
                minX = maxX = startX;
            }

            final int startY = Math.round(-rect.top);
            if (viewHeight < rect.height()) {
                minY = 0;
                maxY = Math.round(rect.height() - viewHeight);
            } else {
                minY = maxY = startY;
            }

            mCurrentX = startX;
            mCurrentY = startY;

            // If we actually can move, fling the scroller
            if (startX != maxX || startY != maxY) {
                mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, 0, 0);
            }
        }

        @Override
        public void run() {

            if (mScroller.isFinished()) {
                return; // remaining post that should not be handled
            }

            if (mScroller.computeScrollOffset()) {

                final int newX = mScroller.getCurrX();
                final int newY = mScroller.getCurrY();

                mSuppMatrix.postTranslate(mCurrentX - newX, mCurrentY - newY);
                setImageViewMatrix(getDrawMatrix());

                mCurrentX = newX;
                mCurrentY = newY;

                // Post On animation
                Compat.postOnAnimation(mImageView, this);
            }
        }
    }

    private static class Compat {

        private static final int SIXTY_FPS_INTERVAL = 1000 / 60;

        static void postOnAnimation(View view, Runnable runnable) {

            if (Build.VERSION.SDK_INT >= 16) {
                postOnAnimationJellyBean(view, runnable);
            } else {
                view.postDelayed(runnable, SIXTY_FPS_INTERVAL);
            }
        }

        @TargetApi(16)
        private static void postOnAnimationJellyBean(View view, Runnable runnable) {

            view.postOnAnimation(runnable);
        }
    }
}
